package com.first.nell.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.first.nell.R
import com.first.nell.base.BaseEditAction
import com.first.nell.base.BaseFormAction
import com.first.nell.databinding.ViewFirstNellLoginMobileInputBinding
import com.first.nell.extend.*
import com.first.nell.utils.UserStateUtil

/**
<declare-styleable name="FirstNellLoginAccountInput">
<attr name="cwlmiTitle" format="string" />
<attr name="cwlmiTextColor" format="color" />
<attr name="cwlmiHint" format="string" />
<attr name="cwlmiDelImageRes" format="reference" />
<attr name="cwlmiDelImageHidden" format="boolean" />
<attr name="cwlmiPreHintHidden" format="boolean" />
</declare-styleable>
 * */
class LoginMobileInput : RelativeLayout, BaseFormAction,
    BaseEditAction {

    lateinit var mFirstNellViewFirstNellBinding: ViewFirstNellLoginMobileInputBinding
    private lateinit var vFirstNellRootFirstNellView: View

    private var cwlmiTextColor: Int = 0
    private var cwlmiHintColor: Int = 0
    private var cwlmiTitle: String? = null
    private var cwlmiText: String? = null
    private var cwlmiHint: String? = null
    private var cwlmiDelImageRes: Int = 0
    private var cwlmiDelImageHidden: Boolean = false
    private var cwlmiPreHintHidden: Boolean = false
    private var cwlmiPreHintLineHidden: Boolean = false
    private var cwlmiPreHintText: String? = null
    private var cwlmiIsTitleBold: Boolean = true
    private var cwlmiTitleSize: Float = 0F

    private var mFirstNellSupportFirstNellFragmentFirstNellManager: FragmentManager? = null

    private var mFirstNellTempFirstNellInputFirstNellValue: String = ""
    private var mFirstNellOnFirstNellActionFirstNellClickFirstNellListener: (Int) -> Unit = {}
    private var mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.LoginMobileInput)
                cwlmiTextColor = array.getColor(
                    R.styleable.LoginMobileInput_cwlmiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwlmiText =
                    array.getString(R.styleable.LoginMobileInput_cwlmiText)

                cwlmiTitle =
                    array.getString(R.styleable.LoginMobileInput_cwlmiTitle)

                cwlmiHintColor = array.getColor(
                    R.styleable.LoginMobileInput_cwlmiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwlmiHint =
                    array.getString(R.styleable.LoginMobileInput_cwlmiHint)

                cwlmiDelImageRes =
                    array.getResourceId(
                        R.styleable.LoginMobileInput_cwlmiDelImageRes,
                        R.drawable.first_nell_close
                    )
                cwlmiDelImageHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiDelImageHidden,
                    false
                )

                cwlmiPreHintHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiPreHintHidden,
                    false
                )

                cwlmiPreHintLineHidden = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiPreHintLineHidden,
                    false
                )

                cwlmiPreHintText =
                    array.getString(R.styleable.LoginMobileInput_cwlmiPreHintText)

                cwlmiIsTitleBold = array.getBoolean(
                    R.styleable.LoginMobileInput_cwlmiIsTitleBold,
                    false
                )

                cwlmiTitleSize = array.getDimension(
                    R.styleable.LoginMobileInput_cwlmiTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                array.recycle()
            }
        }
        context?.let {
            vFirstNellRootFirstNellView =
                View.inflate(it, R.layout.view_first_nell_login_mobile_input, this)
            mFirstNellViewFirstNellBinding =
                ViewFirstNellLoginMobileInputBinding.bind(vFirstNellRootFirstNellView)
            initFirstNellSubviews()
        }
    }

    override fun initFirstNellSubviews() {
        try {
            mFirstNellViewFirstNellBinding.textLoinAccountTitle.text = cwlmiTitle
            mFirstNellViewFirstNellBinding.textLoinAccountTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwlmiTitleSize
            )
            if (cwlmiIsTitleBold) {
                mFirstNellViewFirstNellBinding.textLoinAccountTitle.addFirstNellBoldFirstNellStyle()
            } else {
                mFirstNellViewFirstNellBinding.textLoinAccountTitle.addFirstNellNormalFirstNellStyle()
            }

            mFirstNellViewFirstNellBinding.editLoinAccount.setText(cwlmiText)
            mFirstNellViewFirstNellBinding.editLoinAccount.setTextColor(cwlmiTextColor)

            mFirstNellViewFirstNellBinding.editLoinAccount.hint = (cwlmiHint)
            mFirstNellViewFirstNellBinding.editLoinAccount.setHintTextColor(cwlmiHintColor)

            mFirstNellViewFirstNellBinding.imageLoginAccountDel.setImageResource(cwlmiDelImageRes)

            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.setOnClickListener {
                mFirstNellOnFirstNellActionFirstNellClickFirstNellListener.invoke(0)
            }

            mFirstNellViewFirstNellBinding.imageLoginAccountDel.setOnClickListener {
                mFirstNellOnFirstNellActionFirstNellClickFirstNellListener.invoke(0)
            }

            mFirstNellViewFirstNellBinding.textLoinAccountPreHint.text = cwlmiPreHintText

            if (cwlmiPreHintHidden) {
                mFirstNellViewFirstNellBinding.textLoinAccountPreHint.visibility = GONE
            } else {
                mFirstNellViewFirstNellBinding.textLoinAccountPreHint.visibility = VISIBLE
            }

            if (cwlmiPreHintLineHidden) {
                mFirstNellViewFirstNellBinding.vLoinAccountPreHintLine.visibility = GONE
            } else {
                mFirstNellViewFirstNellBinding.vLoinAccountPreHintLine.visibility = VISIBLE
            }

            mFirstNellViewFirstNellBinding.editLoinAccount.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isFirstNellCompleted()
                    val gContent = getFirstNellContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mFirstNellTempFirstNellInputFirstNellValue,
                                false
                            )
                        ) {
                            try {
                                mFirstNellTempFirstNellInputFirstNellValue = gContent
                                recordFirstNellInputFirstNellEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                    val tempContent = getFirstNellContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlmiDelImageHidden) {
                            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                        mFirstNellViewFirstNellBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.main_purple
                            )
                        )
                    } else {
                        mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility = GONE
                        mFirstNellViewFirstNellBinding.textLoinAccountPreHint.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.main_purple
                            )
                        )
                    }
                }
            }
            mFirstNellViewFirstNellBinding.editLoinAccount.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getFirstNellContent()
                    if (tempContent.isNotBlank()) {
                        if (cwlmiDelImageHidden) {
                            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility = GONE
                        } else {
                            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility =
                                VISIBLE
                        }
                    } else {
                        mFirstNellViewFirstNellBinding.llLoginAccountDelBg.visibility = GONE
                    }
                    //回调
                    mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener.invoke(
                        tempContent
                    )
                }
            })

            mFirstNellViewFirstNellBinding.llLoginAccountDelBg.setOnClickListener {
                mFirstNellViewFirstNellBinding.editLoinAccount.setText("")
            }
            mFirstNellViewFirstNellBinding.imageLoginAccountDel.setOnClickListener {
                mFirstNellViewFirstNellBinding.editLoinAccount.setText("")
            }

            //增加星号显示
            mFirstNellViewFirstNellBinding.textLoinAccountTitle.addFirstNellHighlightFirstNellStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setFirstNellContent(content: String) {
        mFirstNellViewFirstNellBinding.editLoinAccount.setText(content)
    }

    fun getFirstNellContent(): String {
        return mFirstNellViewFirstNellBinding.editLoinAccount.text.toString().trim()
    }

    fun isFirstNellCompleted(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            mFirstNellViewFirstNellBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.first_nell_form_input_error)
            mFirstNellViewFirstNellBinding.llLoginAccountErrTipBg.visibility = VISIBLE
            return false
        }

        mFirstNellViewFirstNellBinding.llLoginAccountErrTipBg.visibility = GONE
        mFirstNellViewFirstNellBinding.rlLoinAccountBg.setBackgroundResource(R.drawable.first_nell_form_input_login)
        return true
    }

    fun isFirstNellCompletedFirstNellSlient(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toFirstNellBeFirstNellFocusFirstNellPointFirstNellAndFirstNellShowFirstNellInputFirstNellKeyboard() {
        try {
            mFirstNellViewFirstNellBinding.editLoinAccount.isFocusable = true
            mFirstNellViewFirstNellBinding.editLoinAccount.isFocusableInTouchMode = true
            mFirstNellViewFirstNellBinding.editLoinAccount.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(
                            mFirstNellViewFirstNellBinding.editLoinAccount,
                            0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toFirstNellBeFirstNellFocusFirstNellPoint() {
        try {
            mFirstNellViewFirstNellBinding.editLoinAccount.isFocusable = true
            mFirstNellViewFirstNellBinding.editLoinAccount.isFocusableInTouchMode = true
            mFirstNellViewFirstNellBinding.editLoinAccount.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setFirstNellInputFirstNellHint(hint: String) {
        val hintFormat = hint.toFirstNellPhoneFirstNellNumberFirstNellInputFirstNellHint()
        mFirstNellViewFirstNellBinding.editLoinAccount.hint = hintFormat
    }

    fun setFirstNellPreFirstNellHint(hint: String) {
        mFirstNellViewFirstNellBinding.textLoinAccountPreHint.text = hint
    }

    override fun setFirstNellFragmentFirstNellManager(manager: FragmentManager) {
        mFirstNellSupportFirstNellFragmentFirstNellManager = manager
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellClickFirstNellListener = listener
    }

    override fun setFirstNellOnFirstNellTextFirstNellChangedFirstNellListener(listener: (String) -> Unit) {
        mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener = listener
    }

    override fun setFirstNellTitle(title: String) {
        cwlmiTitle = title
        mFirstNellViewFirstNellBinding.textLoinAccountTitle.text = cwlmiTitle
        //增加星号显示
        mFirstNellViewFirstNellBinding.textLoinAccountTitle.addFirstNellHighlightFirstNellStyle(
            mutableListOf("*"),
            ContextCompat.getColor(context, R.color.main_red)
        )
    }

    override fun setFirstNellDetail(detail: String) {

    }

    override fun setFirstNellHint(hint: String) {
        setFirstNellInputFirstNellHint(hint)
    }

    override fun setFirstNellDetailFirstNellColor(detailColor: Int) {

    }

    override fun setFirstNellTitleFirstNellColor(titleColor: Int) {

    }

    fun cleanFirstNell() {
        mFirstNellViewFirstNellBinding.editLoinAccount.setText(null)
    }

    @SuppressLint("SetTextI18n")
    fun updateFirstNellLanguage(path: String, customer: String) {
        //hint
        mFirstNellViewFirstNellBinding.editLoinAccount.hint = customer
        setFirstNellTitle(context.getString(R.string.first_nell_enter_the_phone_number))

        //区号
//        val areaCode = CountryEnum.NIGERIA.areaCode
        val areaCode = UserStateUtil.mFirstNellPhoneFirstNellCode
        mFirstNellViewFirstNellBinding.textLoinAccountPreHint.text = areaCode
    }
}